#include "rfile.h"
#include "utility.h"

rfile::rfile()
{

}
rfile::~rfile(){};

bool rfile::isExist(std::string filename)
{
    struct stat stFileInfo;
    int intStat;
    intStat = stat(filename.c_str(),&stFileInfo);
    return !intStat;
}

bool rfile::copyFile(std::string FileFrom, std::string FileTo, bool isRecover, std::string *strErrMsg)
{
    if (!isExist(FileFrom))
    {
        *strErrMsg = "The source file is not exist or can not read.";
        return false;
    }

    if (isExist(FileTo))
    {
        if (!isRecover)
        {
            *strErrMsg = "The target file is exist.";
            return false;
        }
        else
        {
            del(FileTo);
        }
    }

    std::ifstream ifs(FileFrom.c_str(), std::ios::binary);
    std::ofstream ofs(FileTo.c_str(), std::ios::binary);
    ofs << ifs.rdbuf();
    ifs.close();
    ofs.close();
    return true;
}

bool rfile::copyFile(std::string FileFrom, std::string FileTo, bool isRecover)
{
    std::string strErrMsg;
    return copyFile(FileFrom, FileTo, isRecover, &strErrMsg);
}

bool rfile::copyFile(std::string FileFrom, std::string FileTo)
{
    std::string strErrMsg;
    return copyFile(FileFrom, FileTo, true, &strErrMsg);
}

bool rfile::copyFile(std::string FileFrom, std::string FileTo, std::string *strErrMsg)
{
    return copyFile(FileFrom, FileTo, true, strErrMsg);
}

bool rfile::del(std::string strFileName)
{
    if (isExist(strFileName))
    {
        try{
            std::remove(strFileName.c_str());
            return true;
        }catch(...){
            return false;
        }
    }
    return true;
}

long rfile::getFileLastModifyDateTime(std::string strFileName)
{
    if (rfile::isExist(strFileName))
    {
		struct stat st;
		const char* charFileName = strFileName.c_str();
				
		if (stat(charFileName, &st) == 0 ) 
		{
			return st.st_mtime;
		}else{
			return 0;
		}
    }
    else
    {
		return 0;
	}
}
